/*
 * http访问 封装
 * @author long@7road.com
 */
package com.pclong.commons.http;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.GZIPInputStream;

import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.params.*;
import org.apache.http.conn.params.*;
import org.apache.http.entity.*;
import org.apache.http.entity.mime.*;
import org.apache.http.entity.mime.content.*;
import org.apache.http.impl.client.*;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.*;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

/**
 * http访问 封装
 * @author long@7road.com
 */
public class HttpWebClient {

    private String charset = "GBK";
    private HttpClient httpclient;

    /**
     * 构造方法
     */
    public HttpWebClient() {
        httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        httpclient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS);
    }

    /**
     * 构造方法
     * @param charset
     */
    public HttpWebClient(String charset) {
        this();
        this.charset = charset;
    }

    /**
     * 构造方法 ：使用代理连接
     * @param ip
     * @param port
     */
    public HttpWebClient(String ip, int port) {
        this();
        HttpHost proxy = new HttpHost(ip, port);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    private HttpGet setHttpGetHeader(HttpGet httpGet, Map<String, Object> headers) {
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue().toString());
            }
        }
        return httpGet;
    }

    public String get(HttpGet httpget) throws IOException {
        HttpResponse response = httpclient.execute(httpget);
        return this.getResponseBodyAsString(response);
    }

    public String get(Map<String, Object> headers, String url) throws IOException {
        HttpGet httpget = new HttpGet(url);
        httpget = this.setHttpGetHeader(httpget, headers);
        return this.get(httpget);
    }

    private String get(String url, String headerAccept) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", headerAccept);
        return this.get(headers, url);
    }

    public String get(String url) throws IOException {
        return this.get(url, WebHeaderConstant.WEB_ACCEPT_XML);
    }

    public String getJson(String url) throws IOException {
        return this.get(url, WebHeaderConstant.WEB_ACCEPT_JSON);
    }

    public byte[] getFile(HttpGet httpget) throws IOException {
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        byte[] bs = EntityUtils.toByteArray(entity);
        if (entity != null) {
            entity.consumeContent();
        }
        return bs;
    }

    public byte[] getFile(Map<String, Object> headers, String url) throws IOException {
        HttpGet httpget = new HttpGet(url);
        httpget = this.setHttpGetHeader(httpget, headers);
        return this.getFile(httpget);
    }

    public byte[] getFile(String url) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_XML);
        return this.getFile(headers, url);
    }

    public byte[] getFile(String url, File file) throws IOException {
        byte[] bs = this.getFile(url);
        FileOutputStream output = new FileOutputStream(file);
        output.write(bs);
        output.close();
        return bs;
    }

    private HttpPost setHttpPostHeaderAndParams(HttpPost httpPost, Map<String, Object> headers, Map<String, Object> params) throws UnsupportedEncodingException {
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue().toString());
            }
        }
        //
        List nvps = new ArrayList<NameValuePair>();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        return httpPost;
    }

    public String post(HttpPost httppost) throws IOException {
        HttpResponse response = httpclient.execute(httppost);
        return this.getResponseBodyAsString(response);
    }

    public String post(Map<String, Object> headers, String url, Map<String, Object> params) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        this.setHttpPostHeaderAndParams(httpPost, headers, params);
        return this.post(httpPost);
    }

    public String post(String url, Map<String, Object> params) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_XML);
        return this.post(headers, url, params);
    }

    public String postJson(String url, Map<String, Object> params) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_JSON);
        return this.post(headers, url, params);
    }

    public String post(HttpPost httppost, String str) throws IOException {
        StringEntity reqEntity = new StringEntity(str);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        return this.getResponseBodyAsString(response);
    }

    public String post(Map<String, Object> headers, String url, String str) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        this.setHttpPostHeaderAndParams(httpPost, headers, null);
        return this.post(httpPost, str);
    }

    public String post(String url, String str) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_XML);
        return this.post(headers, url, str);
    }

    public String postJson(String url, String str) throws IOException {
        Map<String, Object> headers = this.getCommonHeader();
        headers.put("Accept", WebHeaderConstant.WEB_ACCEPT_JSON);
        return this.post(headers, url, str);
    }

    public String uploadFile(HttpPost httppost, File file) throws IOException {
        FileBody fileBody = new FileBody(file);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("file", fileBody);
        // 设置请求
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        return this.getResponseBodyAsString(response);
    }

    public void close() {
        httpclient.getConnectionManager().shutdown();
    }

    // ///////////////////////////////////////////////////////////////
    public HttpClient getHttpclient() {
        return httpclient;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    private String getResponseBodyAsString(HttpResponse response) throws IOException {
        String html = null;
        GZIPInputStream gzin;
        if (response.getEntity().getContentEncoding() != null && response.getEntity().getContentEncoding().getValue().toLowerCase().indexOf("gzip") > -1) {
            InputStream is = response.getEntity().getContent();
            gzin = new GZIPInputStream(is);

            InputStreamReader isr = new InputStreamReader(gzin, "iso-8859-1");
            java.io.BufferedReader br = new java.io.BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String tempbf;
            while ((tempbf = br.readLine()) != null) {
                sb.append(tempbf);
                sb.append("\r\n");
            }
            isr.close();
            gzin.close();
            html = sb.toString();
            html = new String(html.getBytes("iso-8859-1"), this.charset);
        } else {
            HttpEntity entity = response.getEntity();
            html = EntityUtils.toString(entity, this.charset);
            if (entity != null) {
                entity.consumeContent();
            }
        }
        return html;
    }

    private Map<String, Object> getCommonHeader() {
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("Accept-Charset", WebHeaderConstant.WEB_ACCEPT_CHARSET);
        headers.put("Accept-Encoding", WebHeaderConstant.WEB_ACCEPT_ENCODING);
        headers.put("Accept-Language", WebHeaderConstant.WEB_ACCEPT_LANGUAGE);
        headers.put("User-Agent", WebHeaderConstant.WEB_USER_AGENT);
        return headers;
    }

//    JAVA 压缩文件
    public static void main(String[] args) {
        try {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(new FileInputStream(args[0]), "ISO8859_1"));
            FileOutputStream f = new FileOutputStream(args[0] + ".zip");
            CheckedOutputStream ch = new CheckedOutputStream(f, new CRC32());
            ZipOutputStream out = new ZipOutputStream(
                    new BufferedOutputStream(ch));

            int c;
            out.putNextEntry(new ZipEntry(args[0]));
            while ((c = in.read()) != -1) {
                out.write(c);
            }
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
